<template>
  <el-date-picker
    v-model="rangeDate"
    type="datetimerange"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    range-separator="-"
    value-format="YYYY-MM-DD HH:mm:ss"
    date-format="YYYY/MM/DD ddd"
    time-format="A hh:mm:ss"
    :disabled-date="disabledDate"
    @visible-change="handleVisibleChange"
    @calendar-change="handleCalendarChange"
    @change="change"
    @clear="clear"
  />
</template>

<script setup>
import { ref } from 'vue';
const rangeDate = ref([]);
const chooseDay = ref(null); // 选择的第一个日期
const handleCalendarChange = (val) => {
  // 选择的第一个日期
  const [chooseFirstDate] = val;
  chooseDay.value = new Date(chooseFirstDate);
};
// 下拉框打开时清除选择的第一个日期，可让用户任意选择开始日期
const handleVisibleChange = (val) => {
  if (val) {
    chooseDay.value = null;
  }
};
const disabledDate = (time) => {
  if (!chooseDay.value) {
    // 选择的第一个日期不存在时可任意选择开始日期
    return false;
  }
  return (
    // 限制选择的日期范围，选择第一个日期的前后30天
    time.getTime() < chooseDay.value.getTime() - 90 * 24 * 3600000 ||
    time.getTime() > chooseDay.value.getTime() + 90 * 24 * 3600000
  );
};
const emit = defineEmits(['TimeChild']);
const Timecustomize = () => {
  emit('TimeChild', rangeDate.value);
};
const change = () => {
  Timecustomize();
};
const clear = () => {
  rangeDate.value = [];
};
defineExpose({
  clear,
});
</script>
